<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 363359328
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;

class UserlevelController extends AdminBaseController
{
	function index(){
		$rows = Db::name('user_level')->where('delete_at',0)->select();
		$this->assign('rows',$rows);
		return $this->fetch();
	}


	function add(){
		if(request()->isPost()){
			$data = input('param.');
			if(empty($data['title'])){
				return $this->error('名称不能为空');
			}
			
			// if($data['level']>1){
			// 	$row = model('UserLevel')->where('delete_at',0)->order('level desc')->find(); //获取已有最大级别
			// 	if($row){
			// 		if($data['invite_num'] <=$row['invite_num'] || $data['group_num']<= $row['group_num']){
			// 			return $this->error('直推人数和团队人数必须大于上一级的对应数量');
			// 		}
			// 	}
			// }
			model('UserLevel')->allowField(true)->save($data);
			cache('all_level',null);
			$this->success('操作成功',url('index'));
		}
		$level = Db::name('user_level')->where('delete_at',0)->max('level')+1;
		$this->assign('level',$level);
		$this->assign('action',url('userlevel/add'));
		$this->assign('row',[]);
		return $this->fetch('edit');
	}


	function edit(){
		$id = input('param.id/d');
		if($id<=0) exit('非法操作');
		if(request()->isPost()){
			$data = input('param.');
			if(empty($data['title'])){
				return $this->error('名称不能为空');
			}
			$updata['title'] = $data['title'];
			$updata['invite_num'] = $data['invite_num'];
			$updata['previous_level_num'] = $data['previous_level_num'];
			$updata['group_num'] = $data['group_num'];
			$updata['level'] = $data['level'];
			$updata['active_back_rate'] = $data['active_back_rate'];
			$updata['profit_back_rate'] = $data['profit_back_rate'];

			model('UserLevel')->where('id',$id)->update($updata);
			cache('all_level',null);
			$this->success('操作成功',url('index'));
		}
		$level = Db::name('user_level')->where('delete_at',0)->max('level')+1;
		$row = model('UserLevel')->where('id',$id)->find();
		$this->assign('level',$level);
		$this->assign('action',url('userlevel/edit'));
		$this->assign('row',$row);
		return $this->fetch('edit');
	}


	function delete(){
		$id = input('param.id/d');
		if($id<=0) exit('非法操作');
		$row = model('UserLevel')->where('id',$id)->update(['delete_at'=>time()]);
		cache('all_level',null);
		$this->success('操作成功',url('index'));
	}

}